package com.cn.web;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

@RestController
@Slf4j
@RequestMapping("lua")
public class LuaController {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    public static final String queueName = "testQueue";

    private volatile Boolean swi = true;

    @PostConstruct
    public void init() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                List<byte[]> list = new ArrayList<>();
                String val = null;
                while (swi) {
                    try {
                        list = stringRedisTemplate.execute(new RedisCallback<List<byte[]>>() {
                            @Override
                            public List<byte[]> doInRedis(RedisConnection connection) throws DataAccessException {
                                return connection.bLPop(1000, queueName.getBytes());
                            }
                        });
                    } catch (Exception e) {
                    }

                    if(!list.isEmpty()){
                        val =  new String(list.get(1));
                        log.info("队列消费的值[{}]", val);
                        list.clear();
                    }

                }
            }
        }).start();


    }

    @PreDestroy
    public void destroy() {
        swi = false;


    }

    @GetMapping("put")
    public String put(String val) {
        stringRedisTemplate.opsForList().leftPush(queueName, val);
        return "OK";
    }
}
